package com.ruoyi.business.config;

import com.ruoyi.business.service.S7VariableManagerService;
import com.ruoyi.business.service.s7.S7ConnectionManagerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * S7协议应用启动配置
 * 在Spring Boot应用启动完成后，自动初始化S7连接
 *
 * @author qiancheng
 * @date 2025-08-30
 */
@Component
@Order(2) // 确保在S7VariableManagerService(Order=1)之后执行
public class S7ApplicationStartupConfig implements ApplicationRunner {

    private static final Logger log = LoggerFactory.getLogger(S7ApplicationStartupConfig.class);

    @Autowired
    private S7VariableManagerService s7VariableManagerService;

    @Autowired
    private S7ConnectionManagerService s7ConnectionManagerService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("======= 启动S7协议服务 =======");

        try {
            // 等待变量管理服务完成加载
            Thread.sleep(2000);

            // 检查是否有激活的变量配置
            int totalVariables = s7VariableManagerService.getTotalActiveVariablesCount();
            int plcDeviceCount = s7VariableManagerService.getPlcDeviceCount();

            if (totalVariables == 0) {
                log.warn("未找到激活的S7变量配置，跳过连接初始化");
                return;
            }

            log.info("检测到 {} 台PLC设备，共 {} 个激活变量", plcDeviceCount, totalVariables);

            // 初始化所有PLC连接（使用优化后的S7连接管理服务）
            s7ConnectionManagerService.initializeAllConnections();

            // 输出连接状态统计
            Thread.sleep(3000); // 等待连接初始化完成
            java.util.Map<String, Boolean> connectionStatus = new java.util.HashMap<>();
            for (String plcIp : s7VariableManagerService.getAllPlcIps()) {
                connectionStatus.put(plcIp, s7ConnectionManagerService.isConnected(plcIp));
            }
            long connectedCount = connectionStatus.values().stream().mapToLong(status -> status ? 1 : 0).sum();

            log.info("S7连接初始化完成，连接成功: {}/{}", connectedCount, plcDeviceCount);

        } catch (Exception e) {
            log.error("S7协议服务启动失败", e);
        }

        log.info("======= S7协议服务启动完成 =======");
    }
}
